import {getInfo, getMenu as getUserMenu, userLogin} from "../../api/user";
import {removeToken, setToken} from "../../uilts/token";

const state = {
  userInfo:{},
  userMenu:[],
}
const mutations = {
  SET_USERINFO(state,info){
    state.userInfo = info
  },
  SET_USERMENU(state,menu){
    state.userMenu =  menu
    state.userInfo.role = menu[0].meta.role
  },
  REST_USER(state){
    state.userInfo = {}
    state.userMenu = []
  }
}
const actions = {
  login(ctx,userInfo){
    return new Promise(async resolve => {
      const { token } = await userLogin(userInfo)
      setToken(token)
      resolve()
    })
  },
  getUserInfo({commit}){
    return new Promise(async resolve => {
      const info = await getInfo()
      commit('SET_USERINFO',info)
      resolve()
    })
  },
  getMenu({ commit }){
    return new Promise(async resolve => {
      const res = await getUserMenu()
      commit('SET_USERMENU',res)
      resolve()
    })
  },
  logout({commit}){
    return new Promise(resolve => {
      removeToken()
      commit('REST_USER')
      resolve()
    })
  }
}


export default {
  state,
  mutations,
  actions
}
